package com.example.controller;

import com.example.service.EtcdService;
import com.example.service.SysServerService;
import io.etcd.jetcd.KeyValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@RestController
public class SysTestController implements InitializingBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private EtcdService etcdService;

    @Resource
    private SysServerService sysServerService;

    /****
     * 设置kv带有效期
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "putByTls")
    public String putByTls() throws Exception {
        String uuid = UUID.randomUUID().toString();
        etcdService.putByTls("/yyyyy/" + uuid, uuid.getBytes(StandardCharsets.UTF_8), 60);
        return uuid;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //this.etcdService.putAutoLease("/nodes/" + sysServerService.getServerKey(), sysServerService.getServerKey().getBytes(StandardCharsets.UTF_8), 2);
    }

    @RequestMapping(value = "getNodeList")
    public void getNodeList() throws Exception {
        List<KeyValue> keyValues = etcdService.getChildList("/nodes/");
        for (KeyValue keyValue : keyValues) {
            logger.info("key: " + keyValue.getKey().toString(StandardCharsets.UTF_8) + " value: " + keyValue.getValue().toString(StandardCharsets.UTF_8));
        }
    }
}

